/**
 * cli https://developers.weixin.qq.com/miniprogram/dev/devtools/cli.html#%E8%87%AA%E5%8A%A8%E9%A2%84%E8%A7%88
 * 
 * npm install miniprogram-ci --save
 * ci https://developers.weixin.qq.com/miniprogram/dev/devtools/ci.html
 */

const ci = require('miniprogram-ci')
const { spawn, spawnSync } = require('child_process')
let log = console.log

let argv = process.argv
let command = argv[2]
let subcommand = argv[3]
let pwd = process.env.PWD
let mpcli = '/Applications/wechatwebdevtools.app/Contents/MacOS/cli'
let privateKeyPath = `${pwd}/res/upload.key`
let projectPath = `${pwd}/dist/dev/mp-weixin`
let packageJson = require(`${pwd}/package.json`)
let desc = packageJson.versionDesc||''
let version = packageJson.version
argv.forEach(v=>{
  if(v==='--build') {
    projectPath = `${pwd}/dist/build/mp-weixin`
  }else if(v.startsWith('--v')) {
    version = v.replace('--v','')
  }else if(v.startsWith('--desc')) {
    desc = v.replace('--desc','')
  }
})
let qrcodeOutputDest  = `${projectPath}/preview.jpg`
let configFile = `${projectPath}/project.config.json`
let configJson = require(configFile)
const project = new ci.Project({
  appid: configJson.appid,
  type: 'miniProgram',
  projectPath: projectPath,
  privateKeyPath: privateKeyPath,
  ignores: ['node_modules/**/*'],
})
const setting = {
  "urlCheck": false,
  "babelSetting": {
    "ignore": [],
    "disablePlugins": [],
    "outputPath": ""
  },
  "ignoreUploadUnusedFiles": true,
  "es6": false,
  "enhance": false,
  "minifyWXSS": true,
  "minified": true
}

function exec(cmd, argv) {
  log('exec:',cmd, argv)

  return new Promise((resolve)=>{
    const shell = spawn(cmd, argv)
    shell.stdout.on('data', data => {
      console.log(data.toString())
    })
    shell.on('close', code => {
      resolve(code)
    })
    shell.on('exit', code => {
      resolve(code)
    })
  })
}
function execSync(cmd, argv) {
  log('execSync:',cmd, argv)
  let ret = spawnSync(cmd, argv)
  return ret.output.reduce((v1, v2)=>v1+'\n'+(v2||''), '')
}
log(`command=${command} subcommand=${subcommand} projectPath=${projectPath} version=${version} desc=${desc}`)


async function doMpOpen() {
  log('doMpOpen')
  exec(mpcli, ['open', '--project', projectPath])
}
async function doMpPreview() {
  log('doMpPreview')
  const previewResult = await ci.preview({
    project,
    desc,
    setting,
    qrcodeFormat: 'image',
    qrcodeOutputDest,
    onProgressUpdate: console.log,
  })
  console.log('res:',previewResult)
  exec('open', [qrcodeOutputDest])
}
async function doMpUpload() {
  log('doMpPreview')
  const uploadResult = await ci.upload({
    project,
    version,
    desc,
    setting,
    onProgressUpdate: console.log,
  })
  console.log('res:',uploadResult)
}


if(command==='mp') {
  if(subcommand==='open') {
    doMpOpen()
  }else if(subcommand==='preview') {
    doMpPreview()
  }else if(subcommand==='upload'){
    doMpUpload()
  }
}
